$(function () {
    getData(0, loadGrid); //load页面gride初始化页面

    var buttonval =null;
    $('#subtype').change(function () {
        buttonval = $(this).children('option:selected').val();
        getData(buttonval,loadGrid); //when subtype select changed
    });

    $("#BtnAdd").bind('click', addResource);//when add button clicked
    $("#BtnUpdate").bind('click',updateResource);
    $('#BtnDel').bind('click',deletResource);


});

var deletResource  = function () {
    var selectsall= $("table > tbody > tr.selected.focus input[type='checkbox']");
    if(selectsall.length<=0){
        layer.msg('请选择需要删除的资源!');

    }else{
        //从treegride中获取已经得到的元素信息
        var  selectval =  selectsall.attr("id");
        var  subtype =  selectsall.attr("subtype");
        layer.confirm('是否真的要删除该菜单项？', {
            btn: ['删除','取消'] //按钮
        }, function(){
            $.ajax({
                url: base + "/private/sys/res/del?id="+selectval,
                data: {},
                type: "POST",
                async: false,
                success: function (res) {
                    layer.msg('已成功删除！', {
                        time: 1000, //20s后自动关闭
                    });
                    window.parent.location.reload();
                },
                fail: function (res) {
                    layer.msg('系统错误！', {
                        icon: 5
                    });
                }
            });
        });
    }

};

//更新表单
var updateResource=function () {
    // var arr = '';$("input[type='checkbox'] :checked").each(function(i, n){ arr[i] = $(this).val();});
    var selectsall= $("table > tbody > tr.selected.focus input[type='checkbox']");
    if(selectsall.length<=0){
        layer.msg('请选择需要编辑的资源!');
        return;
    }else{
        //从treegride中获取已经得到的元素信息
          var  selectval =  selectsall.attr("id");
        $.each(tree1.data.rows,function (index, item) {
              if(selectval ==  item.id){
                  selectsall = item;

              }
        })
    }

    //弹出编辑框
    layui.use(['form', 'laytpl', 'laydate', 'laypage', 'layer'], function () {
        form = layui.form(),
            laytpl = layui.laytpl,
            layer = layui.layer;
        layopenChild();  //弹出资源按钮编辑页面
        openUpdateLayer(selectsall,contentDiv());
        initSubType(selectsall.subtype); //初始化资源类型
        initParentSelect(selectsall.subtype,selectsall.pid);
        changeParentSelect(); //根据资源类型获取相应菜单
        initSystemStatus(selectsall.state);  // 初始化启用/禁用
        btnclick();
    });

    //打开编辑框
    openUpdateLayer(selectsall,contentDiv());
};


var openUpdateLayer = function (selectsall,content) {
        layer.open({
            id:'resourceEditForm'
            ,type:1
            , title: '更新资源信息'
            , content: content
            , area: ['800px', '600px']
            , btn: ['确认', '取消']
            , yes: function (index, layero) { //确认
                var data = $(layero).find("form").serializeJSON();
                //提交用户验证
                if(data.name == ""){
                    var obj = $("input[name='name']");
                    obj.focus();
                    layer.tips('请填写此字段!', obj);
                    return false;
                }
                if(data.url == ""){
                    var obj = $("input[name='url']");
                    obj.focus();
                    layer.tips('请填写此字段!', obj);
                    return false;
                }
                if(data.subtype == ""){
                    alert("请选择资源类型!");
                    return false;
                }
                if(data.parentId == ""){
                    alert("请选择此url的上级菜单!");
                    return false;
                }
                if(data.state == ""){
                    alert("请选择启用或者禁用此菜单项!");
                    return false;
                }

                $.ajax({
                    url: base + "/private/sys/res/updateSave" ,
                    data: {"data":JSON.stringify(data),"id":selectsall.id},
                    async: false,
                    success: function (res) {
                       // alert(JSON.stringify(res));
                        parent.layer.close(index);
                        window.location.reload();
                    },
                    fail: function (res) {
                        layer.msg('系统错误！', {
                            icon: 5
                        });
                    }
                });
            },success:function (index, layero) {
                //打开成功之后需要将值绑定到对应表单
               // alert($(layero));
                $("input[name='name']").attr("value",selectsall.name);
                $("input[name='url']").attr("value",selectsall.url);
                $("input[name='button']").attr("value",selectsall.button);
                // $("input[name='descript']").attr("value",selectsall.descript);

            }
        });
};


//make a window of upload
var addResource = function () {
    layui.use(['form', 'laytpl', 'laydate', 'laypage', 'layer'], function () {
        form = layui.form(),
            laytpl = layui.laytpl,
            layer = layui.layer;
        initSubType(); //初始化资源类型
        changeParentSelect(); //根据资源类型获取相应菜单
        initSystemStatus();  // 初始化启用/禁用
        layopen(contentDiv());
        layopenChild();  //弹出资源按钮编辑页面
        btnclick();
    });
};



var  layopenChild=function () {
    $(document).on('click','#textarea_btn',function(){
        layer.open({
            id:'resourceBntAdd'
            ,title: '增加资源按钮'
            , content: contentEditResource()
            , area: ['500px', '400px']
            , btn: ['确认', '取消']
            , yes: function (index, layero) { //确认
                var data = $(layero).find("form").serializeJSON();
                var elems = $("select[name='buts']").find('option');
                var  str = "";
                $.each(elems,function (index, data) {
                    if($(this).val() !="" &&  $(this).val()  != null){
                        if(index <= elems.length -1){
                            str += $(this).text()+",";
                        }else{
                            str += $(this).text();
                        }
                       //json[$(this).val()] = $(this).text();
                    }
                });
                //alert(str);
                var text_area = window.parent.$("input[name='button']");
                var text_area_val = (text_area.val()==undefined  || text_area.val()== "undefined" )?"":text_area.val();
                text_area.val(text_area_val+str);
                //parent.$("input[name='resBnt']").val(parent.$("input[name='resBnt']").val()+str);
                //alert(index);
                parent.layer.close(index);
            }
        });
    });
};



var contentEditResource = function () {
    var content;
    var data = {
        "title": {
            "id":"id",
            "name": "名称:",
            "sign": "标识:",
            "data":"操作:",
            "buts": "增加资源按钮:"
        }, "text": {
            "id":"id",
            "name": "",
            "sign": "",
            "data":"",
            "buts": ""
        }, "input": {
            "id":"hidden",
            "name": "text",
            "sign": "text",
            "btn":"add_btn",
            "data":"btn",
            "buts": "select"
        }, "input_init": {}

    };    var getDiv = "";
    if(dc_update.length>1){
        getDiv = dc_update[0].innerHTML;
    }else{
        getDiv = dc_update.innerHTML;
    }
    laytpl(getDiv).render(data, function (html) {
        content = html;
    });
    return content;
};

var btnclick = function(){
    form.on('submit(add_btn)', function(data){
       // alert(JSON.stringify(data.field));
        var name = data.field.name,sign=data.field.sign;
        if(name == "" || sign == ""){
            return false;
        }
        var option_str = "<option value=\"" + sign + "\" >" + name+ ":" + sign +  "</option>";
        $("select[name='buts']").append(option_str);
        form.render();
        // console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
        // console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
        // console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
        // return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

    form.on('submit(del_btn)', function(data){
        //alert(JSON.stringify(data.field));
        var name = $("select[name='buts'] option:selected").text();
        var sign = $("select[name='buts'] option:selected").val();
        if(name == "" || sign == ""){
            layer.msg('请选择要删除的按钮！', {
                icon: 5
            });
            return false;
        }
        $("select[name='buts'] option:selected").remove();
        form.render();
        // console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
        // console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
        // console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
        // return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
};

var layopen = function (content) {
    layer.open({
        id:'resourceAddForm'
        ,type:1
        , title: '增加资源信息'
        , content: content
        , area: ['800px', '650px']
        , btn: ['确认', '取消']
        , yes: function (index, layero) { //确认
            var data = $(layero).find("form").serializeJSON();
            // alert(JSON.stringify(data));
            //提交用户验证
            if(data.name == ""){
                var obj = $("input[name='name']");
                obj.focus();
                layer.tips('请填写此字段!', obj);
                return false;
            }
            if(data.url == ""){
                var obj = $("input[name='url']");
                obj.focus();
                layer.tips('请填写此字段!', obj);
                return false;
            }
            if(data.subtype == ""){
                alert("请选择资源类型!");
                return false;
            }
            if(data.parentId == ""){
                alert("请选择此url的上级菜单!");
                return false;
            }
            if(data.state == ""){
                alert("请选择启用或者禁用此菜单项!");
                return false;
            }
            $.ajax({
                url: base + "/private/sys/res/addSave" ,
                data: data,
                async: false,
                success: function (res) {
                    res = JSON.parse(res);
                    // alert(res);
                    parent.layer.close(index);
                },
                fail: function (res) {
                    layer.msg('系统错误！', {
                        icon: 5
                    });
                }
            });
        }
    });

};

var contentDiv = function () {
    var content;
    var data = {
        "title": {
            "name": "菜单名称",
            "url": "菜单URL",
            "subtype": "菜单类型",
            "pid": "上级菜单",
            "state": "状态",
            "button": "按钮",
            "descript": "备注"
        }, "text": {
            "name": "",
            "url": "",
            "subtype": "",
            "pid": "",
            "state": "",
            "button": "",
            "descript": ""
        }, "input": {
            "name": "text",
            "url": "text",
            "subtype": "select",
            "pid": "_select",
            "state": "new_select",
            "button": "textarea_btn",
            "descript": "textarea",
        }, "input_init": {}
    };
    var getDiv = "";
    if(dc_update.length>1){
        getDiv = dc_update[0].innerHTML;
    }else{
        getDiv = dc_update.innerHTML;
    }
    laytpl(getDiv).render(data, function (html) {
        content = html;
    });
    return content;
};

var initSubType = function (selected) {
    $.getJSON(base + "/private/sys/res/getSubtype", function (data, status) {
        if (data != null) {
            $("#select").html("");
            var optionstring = "";
            $.each(data, function (i, item) {
                if(selected!=null && selected==item.id){
                 optionstring += "<option value=\"" + item.id + "\" selected='selected'>" + item.code + "</option>";
                }else{
                optionstring += "<option value=\"" + item.id + "\" >" + item.code + "</option>";
                }
            });

            $("#select").html('<option value=""></option>' + optionstring);
        } else {
            $("#select").html('<option value=""></option>');
        }
        form.render();
    });
};

var initSystemStatus = function (state) {
    $.getJSON(base + "/private/sys/res/sysusingstatus", function (data, status) {
        if (data != null) {
            $("#new_select").html("");
            var optionstring = "";
            $.each(data, function (i, item) {
                if( state!=null && state==item.id){
                optionstring += "<option value=\"" + item.id + "\" selected='selected' >" + item.code + "</option>";
                }else{
                optionstring += "<option value=\"" + item.id + "\" >" + item.code + "</option>";
                }
            });

            $("#new_select").html('<option value=""></option>' + optionstring);
        } else {
            $("#new_select").html('<option value=""></option>');
        }
        form.render();
    });
};

var  initParentSelect  = function (subtype,selectval) {
    $.ajax({
        url: base + "/private/sys/res/listNew?subtype="+subtype,
        data: {},
        type: "POST",
        async: false,
        success: function (res) {
            res = JSON.parse(res);
            if (res != null) {
                var optionstring = "";
                $.each(res, function (i, item) {
                    if (selectval != null &&  selectval==item.id) {
                        optionstring += "<option value=\"" + item.id + "\" selected='selected' >" + item.name + "</option>";
                    } else {
                        optionstring += "<option value=\"" + item.id + "\" >" + item.name + "</option>";
                    }
                });
                //alert(optionstring);
                $("#_select").append('<option value=""></option>' + optionstring);
            } else {
                $("#_select").append('<option value=""></option>');
            }
           // alert($("#_select").attr("id"));
            form.render();
        },
        fail: function (res) {
            layer.msg('系统错误！', {
                icon: 5
            });
        }
    });
};

//级联下拉
var changeParentSelect = function () {
    form.on('select(select)', function (value) {
        $.ajax({
            url: base + "/private/sys/res/listNew",
            data: {subtype: value.value},
            type: "POST",
            async: false,
            success: function (res) {
                res = JSON.parse(res);
                if (res != null) {
                    // $("#_select").html("");
                    //TODO  这里做一个标签组 可以实现类似treegride结构,目前使用原生结构
                    var optionstring = "";
                    $.each(res, function (i, item) {
                        // var idlenght = item.id.length;
                        // if(item.pid=='0') {
                        //     optionstring += "<option value=\"" + item.id + "\" >" + item.name + "</option>";
                        // }
                        //     var blankstr="";
                        //    var index = item.id.indexOf(item.pid);
                        //     if (index!=-1) {
                        //         for(var i;i<index;i++){
                        //             blankstr += "  ";
                        //         }
                        //         optionstring += "<option value=\"" + item.id + "\" >" + blankstr + "|_" + item.name + "</option>";
                        //     }else{
                        //         optionstring += "<option value=\"" + item.id + "\" >" + "|_" + item.name + "</option>";
                        //     }

                        if (pid != null &&  pid==item.id) {
                            optionstring += "<option value=\"" + item.id + "\" selected='selected' >" + item.name + "</option>";
                        } else {
                            optionstring += "<option value=\"" + item.id + "\" >" + item.name + "</option>";
                        }
                    });
                    $("#_select").html('<option value=""></option>' + optionstring);
                } else {
                    $("#_select").html('<option value=""></option>');
                }
                form.render();
            },
            fail: function (res) {
                layer.msg('系统错误！', {
                    icon: 5
                });
            }
        });
    });
};




var getData = function (type, func) {
    $.ajax({
        url: base + "/private/sys/res/list?subtype=" + type,
        type: 'json',
        async: false,
        success: function (res) {
            func(JSON.parse(res));
        },
        fail: function (res) {
            layer.msg('系统错误！', {
                icon: 5
            });
        }
    });
};

var loadGrid = function (res) {
    layui.config({base: '../js/system/layui/lay/extend/'}).use(['element', 'laytpl', 'grid', 'treeGrid'], function () {

        var laytpl = layui.laytpl, treegrid = layui.treeGrid;

        treegrid.config.render = function (viewid, data) {
            var view = document.getElementById(viewid).innerHTML;
            return laytpl(view).render(data) || '';
        };

        tree1 = treegrid.createNew({
            elem: 'menu_table',
            view: 'menuTableTpl',
            data: {rows: res},
            id: 'id',
            parentid: 'pid',
            order: 'location',
            singleSelect: true  //支持多选
        });
        tree1.build();
    });
};

